package com.leyou.second.service;

import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.IdWorker;
import com.leyou.common.utils.JsonUtils;
import com.leyou.order.dto.OrderDTO;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * @Author HZN
 * @Date 2020/11/19
 */
@Service
@Transactional
public class SecondService {
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public Long buildOrder(OrderDTO orderDTO) {
        String skuId = String.valueOf(orderDTO.getSeck().getSkuId());
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps("Seckill");
        if (boundHashOps.hasKey(skuId)) {
            Object o = boundHashOps.get(skuId);
            Long stock = Long.valueOf(o.toString());
            if (stock > 0) {
                long orderId = idWorker.nextId();
                UserInfo user = UserHolder.getUser();
                HashMap<String, String> map = new HashMap<>();
                map.put("orderDTO", JsonUtils.toString(orderDTO));
                map.put("orderId", String.valueOf(orderId));
                map.put("userId", user.getId().toString());
                amqpTemplate.convertAndSend(
                        MQConstants.Exchange.SECKILL_EXCHANGE_NAME,
                        MQConstants.RoutingKey.SKU_SECKILL_KEY,
                        map
                );
                String num = String.valueOf((stock - 1));
                boundHashOps.put(skuId, num);
                return orderId;
            } else {
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH_ERROR);
            }
        } else {
            throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH_ERROR);
        }
    }
}
